﻿using Entity;
using IdentityModel;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Reopsitory.Registers;
using Service;
using Service.Registers.Dto;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Service.Registers
{
    public class RegisterService : IRegisterService
    {
        private readonly IRegisterReopsitory registerReopsitory;
        private readonly IConfiguration configuration;

        public RegisterService(IRegisterReopsitory registerReopsitory, IConfiguration configuration)
        {
            this.registerReopsitory = registerReopsitory;
            this.configuration = configuration;
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="registerDto"></param>
        /// <returns></returns>
        public RestFull UserRegister(RegisterDto registerDto)
        {
            var data = registerReopsitory.QueryList(x=>x.UserName==registerDto.UserName);

            if (data == null)
            {
                UserInfo register = new UserInfo();

                register.UserName = registerDto.UserName;
                register.Phone = registerDto.Phone;
                register.Password = registerDto.Password;

                registerReopsitory.Insert(register);

                return new RestFull { Code = 0, Message = "恭喜您，注册成功" };
            }
            else
            {
                if (registerDto.ConfirmPassword != registerDto.Password)
                {
                    return new RestFull { Code = 1, Message = "两次密码不一致" };
                }
                else
                {
                    return new RestFull { Code = 2, Message = "用户名已重复" };
                }
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginDto"></param>
        /// <returns></returns>
        public RestFull UserLogin(LoginDto loginDto)
        {
            var data = registerReopsitory.QueryList(x => x.UserName == loginDto.UserName).FirstOrDefault();

            if (data == null)
            {
                return new RestFull { Code = 1, Message = "用户名不存在" };
            }
            else
            {
                if (loginDto.Password != data.Password)
                {
                    return new RestFull { Code = 2, Message = "密码错误" };
                }
                else
                {
                    //写Session或Cookies换成JWT
                    IList<Claim> claims = new List<Claim> {
                        new Claim(JwtClaimTypes.Id,data.Id.ToString()),
                        new Claim(JwtClaimTypes.Name,data .UserName)
                    };

                    //JWT密钥
                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtConfig:key"]));

                    //算法
                    var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    //过期时间
                    DateTime expires = DateTime.UtcNow.AddHours(10);


                    //Payload负载
                    var token = new JwtSecurityToken(
                        issuer: configuration["JwtConfig:Issuer"],
                        audience: configuration["JwtConfig:Audience"],
                        claims: claims,
                        notBefore: DateTime.UtcNow,
                        expires: expires,
                        signingCredentials: cred
                        );

                    var handler = new JwtSecurityTokenHandler();

                    //生成令牌
                    string jwt = handler.WriteToken(token);

                    return new RestFull { Code = 0, Data = new LoginDto
                    {
                        Id = loginDto.Id,
                        UserName = loginDto.UserName,
                        Token = jwt

                    },Message = "登录成功" };
                }
            }
        }
    }
}
